<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span>个人信息修改</span>
        </div>
      </template>

      <!-- 表单 -->
      <el-form :model="userfForm" label-width="100px" :rules="rules" ref="formRef">
        <!-- 账号 -->
        <el-form-item label="账号" prop="username">
          <el-input v-model="userfForm.username"/>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input v-model="userfForm.password"/>
        </el-form-item>
        <!-- 电话 -->
        <el-form-item label="电话" prop="phone">
          <el-input v-model="userfForm.phone"/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userfForm.email"/>
        </el-form-item>

        <!-- 头像 -->
        <el-form-item label="头像" prop="avatar">
          <el-upload
              class="upload-demo"
              :show-file-list="false"
              accept=".png,.jpg,.jpeg,.gif"
              drag
              :before-upload="handleBeforeUpload"
              :http-request="handleCustomUploadAvatar"
              multiple
          >
            <img
                style="width: 200px; height: 200px"
                v-if="userfForm.avatar"
                :src="userfForm.avatar"
                class="avatar"
                alt="图片"
            />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script lang="ts" setup>
import {ref, reactive, onMounted} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {Plus} from '@element-plus/icons-vue';
import type {User} from '@/types/entity';
import {apiGet, apiPost} from "@/utils/api.ts";
import {useUserStore} from '@/store/modules/user'

let userStore = useUserStore()
// 表单数据
const userfForm = ref<User>({
  userId: userStore.id,
  username: '',
  password: '',
  phone: '',
  email: '',
  avatar: '',
});

// 表单验证规则
const rules = reactive({
  username: [{required: true, message: '账号不能为空', trigger: 'blur'}],
  password: [
    {required: true, message: '密码不能为空', trigger: 'blur'},
  ],
  phone: [{required: true, message: '电话不能为空', trigger: 'blur'}],
  email: [{required: true, message: '邮箱不能为空', trigger: 'blur'}],
  avatar: [{required: true, message: '请上传头像', trigger: 'change'}],
});

// 表单引用
const formRef = ref();

// 提交表单
const submitForm = async () => {
  await formRef.value.validate();
  await apiPost("/user/editByToken",  {
    userId: userStore.id,
    username: userfForm.value.username,
    password: userfForm.value.password,
    phone: userfForm.value.phone,
    email: userfForm.value.email,
    avatar: userfForm.value.avatar,
    type: 2,
  })
};

// 重置表单
const resetForm = () => {
  formRef.value.resetFields();
};

// 上传文件之前的校验
const handleBeforeUpload = (file: any) => {
  const isImage =
      file.type === "image/png" ||
      file.type === "image/jpg" ||
      file.type === "image/jpeg" ||
      file.type === "image/gif";
  if (!isImage) {
    ElMessage.error("上传文件只能是 .png, .jpg, .jpeg, .gif 格式!");
    return false;
  }

  const isLt20M = file.size / 1024 / 1024 < 20;
  if (!isLt20M) {
    ElMessage.error("上传文件大小不能超过 20MB!");
    return false;
  }
  return isImage && isLt20M;
};

// 自定义上传头像
const handleCustomUploadAvatar = async (option: any) => {
  const formData = new FormData();
  formData.append("file", option.file);
  try {
    const {msg} = await apiPost("/upload/img", formData, {
      headers: {"Content-Type": "multipart/form-data"},
    });
    userfForm.value.avatar = msg;
  } catch (error) {
    ElMessage.error("头像上传失败");
  }
};

// 获取用户信息
const getUserInfo = async () => {
  const {data} = await apiGet('/user/getOneByToken');
  userfForm.value = data
};

// 组件挂载完毕
onMounted(() => {
  getUserInfo();
});
</script>
<style scoped lang="scss">
.profile-container {
  padding: 20px;
  display: flex;
  justify-content: center;
}

.profile-card {
  width: 600px;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
}

.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  :deep(.el-upload:hover) {
    border-color: var(--el-color-primary);
  }

  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
}
</style>